<template>
  <j-modal :title="title" :width="width" :visible="visible" :confirmLoading="confirmLoading" :maskClosable="false"
    :keyboard="false" :forceRender="true" v-bind:prefixNo="prefixNo" switchHelp switchFullscreen @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp" :id="prefixNo" style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{ $t('inPrint.cancel') }}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk"
        v-if="!confirmLoading">{{ $t('commodityManagement.preservation') }}</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.customer')">
              <a-input disabled v-decorator.trim="['remark']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.posNo')">
              <a-input disabled :placeholder="$t('setailManagement.posNo')" v-decorator.trim="['custom3']" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')"
              data-step="2" :data-title="$t('setailManagement.documentNo')" :data-intro="$t('popup.theDocumentOpened')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['number']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-col :lg="6" :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.collectionType')" data-step="3"
            :data-title="$t('inPrint.collectionType')" :data-intro="$t('popup.collectionTypesCan')">
            <a-select :placeholder="$t('popup.pleaseSelectPaymentType')" v-decorator="['payType']"
              :dropdownMatchSelectWidth="false">
              <a-select-option v-for="(item, index) in payTypeList" :key="index" :value="item.value">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col :lg="6" :md="12" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('salesManagement.operator')" data-step="3"
            :data-title="$t('salesManagement.operator')" :data-intro="$t('popup.theDataComesMenu')">
            <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']" :readOnly="true" />
          </a-form-item>
        </a-col>
        <a-col :lg="6" :md="12" :sm="24" v-show="false">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-input v-decorator.trim="['creator']" />
          </a-form-item>
        </a-col>

        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{ xs: { span: 24 }, sm: { span: 24 } }" label="">
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="['custom4']"
                style="margin-top:8px;" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="18" :md="12" :sm="24">
            <j-editable-table id="billModal" :ref="refKeys[0]" :loading="materialTable.loading"
              :columns="materialTable.columns" :dataSource="materialTable.dataSource" :minWidth="minWidth"
              :maxHeight="300" disabled :rowNumber="false">
              <!--              <template #buttonAfter>-->
              <!--                <a-row :gutter="24" style="float:left;" data-step="4" :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">-->
              <!--                  <a-col v-if="scanStatus" :md="6" :sm="24">-->
              <!--                    <a-button @click="scanEnter">{{$t('popup.codeScanningEntry')}}</a-button>-->
              <!--                  </a-col>-->
              <!--                  <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">-->
              <!--                    <a-input placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>-->
              <!--                  </a-col>-->
              <!--                  <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">-->
              <!--                    <a-button @click="stopScan">{{$t('popup.stowScanningCode')}}</a-button>-->
              <!--                  </a-col>-->
              <!--                </a-row>-->
              <!--                <a-row :gutter="24" style="float:left;">-->
              <!--                  <a-col :md="24" :sm="24">-->
              <!--                    <a-dropdown>-->
              <!--                      <a-menu slot="overlay">-->
              <!--                        <a-menu-item key="1" @click="handleBatchSetDepot"><a-icon type="setting"/>{{$t('popup.batchSettings')}}</a-menu-item>-->
              <!--                        <a-menu-item v-if="isTenant" key="2" @click="addDepot"><a-icon type="plus"/>{{$t('popup.newWarehouse')}}</a-menu-item>-->
              <!--                      </a-menu>-->
              <!--                      <a-button style="margin-left: 8px">{{$t('popup.warehouseOperation')}} <a-icon type="down" /></a-button>-->
              <!--                    </a-dropdown>-->
              <!--                  </a-col>-->
              <!--                </a-row>-->
              <!--              </template>-->
            </j-editable-table>
          </a-col>
          <div class="sign">
            <a-col :lg="6" :md="12" :sm="24">
              <a-row class="form-row" :gutter="24">
                <a-col :lg="24" :md="6" :sm="6"><br /><br /></a-col>
                <a-col :lg="24" :md="6" :sm="6">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="5"
                    :data-title="$t('inPrint.documentAmount')" :data-intro="$t('popup.theDocumentIsEqual')">
                    <span slot="label" style="font-size: 20px;line-height:20px">{{ $t('inPrint.documentAmount') }}</span>
                    <a-input v-decorator.trim="['totalPrice']" :style="{ color: 'purple' }" :readOnly="true" />
                  </a-form-item>
                </a-col>
                <a-col :lg="24" :md="6" :sm="6">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="6"
                    :data-title="$t('setailManagement.amountCollected')" :data-intro="$t('popup.theCollectionAmountIs')">
                    <span slot="label"
                      style="font-size: 20px;line-height:20px">{{ $t('setailManagement.amountCollected') }}</span>
                    <a-input v-decorator.trim="['changeAmount', validatorRules.changeAmount]" :style="{ color: 'red' }"
                      defaultValue="0" @keyup="onKeyUpGetAmount" :readOnly="showCheckNumber" />
                  </a-form-item>
                </a-col>
                <!-- 有优惠金额权限才会显示 -->
                <a-col :lg="24" :md="6" :sm="6" v-if="btnEnableList.indexOf(9) > -1">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="7"
                    :data-title="$t('financialManagement.preferentialAmount')"
                    :data-intro="$t('popup.pleasediscountMoney')">
                    <span slot="label"
                      style="font-size: 20px;line-height:20px">{{ $t('financialManagement.preferentialAmount') }}</span>
                    <a-input v-decorator.trim="['discountMoney']" :style="{ color: 'red' }" defaultValue="0"
                      @keyup="onKeyUpdiscountMoney" :readOnly="true" />
                  </a-form-item>
                </a-col>
                <a-col :lg="24" :md="6" :sm="6">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="7"
                    :data-title="$t('setailManagement.giveChange')" :data-intro="$t('popup.changeIsEqualToThe')">
                    <span slot="label"
                      style="font-size: 20px;line-height:20px">{{ $t('setailManagement.giveChange') }}</span>
                    <a-input v-decorator.trim="['backAmount']" :style="{ color: 'green' }" :readOnly="true"
                      defaultValue="0" />
                  </a-form-item>
                </a-col>
                <!-- <a-col :lg="24" :md="6" :sm="6">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="8" :data-title="$t('financialManagement.collectionAccount')"
                               :data-intro="$t('popup.theInformationOfThe')">
                    <span slot="label" style="font-size: 20px;line-height:20px">{{$t('financialManagement.collectionAccount')}}</span>
                    <a-select :placeholder="$t('financialManagement.selectCollection')" style="font-size:20px;" v-decorator="[ 'accountId', validatorRules.accountId ]" :dropdownMatchSelectWidth="false">
                      <div slot="dropdownRender" slot-scope="menu">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0;" />
                        <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                             @mousedown="e => e.preventDefault()" @click="addAccount"><a-icon type="plus" /> {{$t('popup.newAccount')}}</div>
                      </div>
                      <a-select-option v-for="(item,index) in accountList" :key="index" :value="item.id">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col> -->

                <a-col :lg="24" :md="6" :sm="6">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.settlementAccount')"
                    data-step="9" :data-title="$t('inPrint.settlementAccount')"
                    :data-intro="$t('popup.ifMultipleAreBox')">
                    <a-select style="width:185px;" :placeholder="$t('popup.selectSettlementAccount')"
                      v-decorator="['accountId', validatorRules.accountId]" :dropdownMatchSelectWidth="false" allowClear
                      @select="selectAccount" @change="onSelectAccount">
                      <div slot="dropdownRender" slot-scope="menu">
                        <v-nodes :vnodes="menu" />
                        <a-divider style="margin: 4px 0;" />
                        <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                          @mousedown="e => e.preventDefault()" @click="addAccount"><a-icon type="plus" />
                          {{ $t('popup.newAccount') }}</div>
                      </div>
                      <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                    <a-tooltip :title="$t('popup.multiAccountDetails')">
                      <a-button type="default" icon="folder" style="margin-left: 8px;" size="small"
                        v-show="manyAccountBtnStatus" @click="handleManyAccount" />
                    </a-tooltip>
                  </a-form-item>
                </a-col>

                <a-col :lg="24" :md="6" :sm="6" v-if="showCheck">
                  <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" data-step="7"
                    :data-title="$t('financialManagement.checkNumber')" :data-intro="$t('popup.changeIsEqualToThe')">
                    <span slot="label"
                      style="font-size: 20px;line-height:20px">{{ $t('financialManagement.checkNumber') }}</span>
                    <a-input v-decorator.trim="['custom1']" :style="{ color: 'green' }" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
          </div>
        </a-row>
      </a-form>
    </a-spin>
    <member-modal ref="memberModalForm" @ok="memberModalFormOk"></member-modal>
    <depot-modal ref="depotModalForm" @ok="depotModalFormOk"></depot-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <batch-set-depot ref="batchSetDepotModalForm" @ok="batchSetDepotModalFormOk"></batch-set-depot>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
  </j-modal>
</template>
<script>
import pick from 'lodash.pick'
import ManyAccountModal from '@/views/bill/dialog/ManyAccountModalV2'
import MemberModal from '../../system/modules/MemberModal'
import DepotModal from '../../system/modules/DepotModal'
import AccountModal from '../../system/modules/AccountModal'
import BatchSetDepot from '../dialog/BatchSetDepot'
import { FormTypes } from '@/utils/JEditableTableUtil'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import { BillModalMixin } from '../mixins/BillModalMixin'
import { getMpListShort, handleIntroJs } from "@/utils/util"
import { getAccount } from '@/api/api'
import JUpload from '@/components/jeecg/JUpload'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import { toDecimal } from '@/utils/calculate'
import { httpAction, getAction } from '@/api/manage'
export default {
  name: "RetailSaleModal",
  mixins: [JEditableTableMixin, BillModalMixin],
  components: {
    MemberModal,
    DepotModal,
    AccountModal,
    BatchSetDepot,
    JUpload,
    ManyAccountModal,
    JDate,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    }
  },
  data() {
    return {
      title: this.$t('setailManagement.operation'),
      width: '1600px',
      moreStatus: false,
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      visible: false,
      operTimeStr: '',
      prefixNo: 'LSCK',
      fileList: [],
      payTypeList: [],
      minWidth: 1100,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      refKeys: ['materialDataTable',],
      activeKey: 'materialDataTable',
      showCheckNumber: false,//金额是否可输入
      showCheck: false,//是否显示支票
      accountIdList: [],
      accountMoneyList: [],
      checkList: [],
      defaultMoneyList: '',
      printData: '',
      materialTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: this.$t('setailManagement.warehouseName'), key: 'depotId', width: '9%', type: FormTypes.select, placeholder: this.$t('inPrint.pleaseTnter') + '${title}', options: [],
            allowSearch: true, validateRules: [{ required: true, message: '${title}' + this.$t('inPrint.cannotTe') }]
          },
          {
            title: this.$t('reportQuery.barcode'), key: 'barCode', width: '12%', type: FormTypes.popupJsh, kind: 'material', multi: true,
            // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
          },
          { title: this.$t('reportQuery.name'), key: 'name', width: '9%', type: FormTypes.normal },
          { title: this.$t('reportQuery.specification'), key: 'standard', width: '6%', type: FormTypes.normal },
          { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.normal },
          { title: this.$t('reportQuery.model'), key: 'model', width: '5%', type: FormTypes.normal },
          { title: this.$t('reportQuery.unit'), key: 'unit', width: '6%', type: FormTypes.normal },
          {
            title: this.$t('reportQuery.quantity'), key: 'operNumber', width: '5%', type: FormTypes.inputNumber, statistics: true,
            validateRules: [{ required: true, message: '${title}' + this.$t('inPrint.cannotTe') }]
          },
          { title: this.$t('reportQuery.unitPrice'), key: 'unitPrice', width: '10%', type: FormTypes.inputNumber },
          { title: this.$t('reportQuery.amount'), key: 'allPrice', width: '5%', type: FormTypes.inputNumber, statistics: true },
          { title: this.$t('purchasingManagement.discountamount'), key: 'discountAllPrice', width: '10%', type: FormTypes.inputNumber, statistics: true },
          { title: this.$t('financialManagement.remarks'), key: 'remark', width: '7%', type: FormTypes.input }
        ]
      },
      confirmLoading: false,
      validatorRules: {
        operTime: {
          rules: [
            { required: true, message: this.$t('popup.pleaseEnterDocumentDate') + '!' }
          ]
        },
        accountId: {
          rules: [
            { required: true, message: this.$t('setailManagement.pleaseAccount') + '!' }
          ]
        },
        number: {
          rules: [
            { required: true, message: this.$t('otherJS.DocumentNoFailure') }
          ]
        },
        changeAmount: {
          rules: [
            { required: true, validator: this.checkChangeAmount }
          ]
        },
      },
      url: {
        add: '/depotHead/addDepotHeadAndDetail',
        edit: '/depotHead/update',
        detailList: '/depotItem/getDetailList'
      }
    }
  },
  created() {
    this.initPayTypeList()
    let realScreenWidth = window.screen.width
    this.minWidth = realScreenWidth < 1500 ? 900 : 1100

  },
  methods: {
    //调用完edit()方法之后会自动调用此方法
    editAfter() {
      this.printData = ''
      this.billStatus = '0'
      this.manyAccountBtnStatus = false
      this.changeColumnHide()
      this.changeFormTypes(this.materialTable.columns, 'snList', 0)
      this.changeFormTypes(this.materialTable.columns, 'batchNumber', 0)
      this.changeFormTypes(this.materialTable.columns, 'expirationDate', 0)
      if (this.action === 'add') {
        this.addInit(this.prefixNo)
        this.fileList = []
        this.$nextTick(() => {
          handleIntroJs(this.prefixNo, 1)
        })
        this.$nextTick(() => {
          this.form.setFieldsValue({ 'payType': '现付', 'getAmount': 0, 'backAmount': 0 })
        })
      } else {
        this.model.operTime = this.model.operTimeStr
        if (this.model.backAmount) {
          this.model.getAmount = (this.model.changeAmount + this.model.backAmount).toFixed(2)
        } else {
          this.model.getAmount = this.model.changeAmount
        }

        if (this.model.payType === '预付款') {
          this.payTypeList = []
          this.payTypeList.push({ "value": "预付款", "text": this.$t('basicInformation.advanceCharge') })
          this.payTypeList.push({ "value": "现付", "text": this.$t('popup.cash') })
        }
        this.model.userName = this.getLocalStorage('pro__Login_Userinfo').username,
          this.model.creator = this.getLocalStorage('pro__Login_Userinfo').id
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'organId', 'operTime', 'number', 'payType', 'remark', 'custom3', 'totalPrice', 'userName', 'creator',
            'discount', 'discountMoney', 'discountLastMoney', 'otherMoney', 'accountId', 'changeAmount', 'getAmount', 'backAmount'))
        });
        // 加载子表数据
        let params = {
          headerId: this.model.id,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
        }
        let url = this.readOnly ? this.url.detailList : this.url.detailList;
        this.confirmLoading = true
        this.requestSubTableData(url, params, this.materialTable, () => {
          this.printData = JSON.stringify(this.materialTable.dataSource)
          this.confirmLoading = false
        });
      }
      //复制新增单据-初始化单号和日期
      if (this.action === 'copyAdd') {
        this.model.id = ''
        this.model.tenantId = ''
        this.copyAddInit(this.prefixNo)
      }
      this.initRetail()
      this.initDepot()
      this.initAccount()
    },
    //提交单据时整理成formData
    classifyIntoFormData(allValues) {
      // let totalPrice = 0
      let billMain = Object.assign(this.model, allValues.formValue)
      let detailArr = allValues.tablesValue[0].values
      billMain.type = '出库'
      billMain.subType = '零售销售'
      billMain.purchaseStatus = 1
      billMain.status = 1
      billMain.defaultNumber = billMain.number
      // for(let item of detailArr){
      //   totalPrice += item.allPrice-0
      // }
      // billMain.totalPrice = totalPrice
      // if(this.fileList && this.fileList.length > 0) {
      //   billMain.fileName = this.fileList
      // } else {
      //   billMain.fileName = ''
      // }
      // 多账户或者 单银行账户，且找零大于0时重置 accountId
      let accountId = this.form.getFieldValue('accountId')
      let item = this.accountList.find(v => v.id === accountId)
      if (billMain.accountId === 0 || (billMain.backAmount > 0 && !this.showCheckNumber && item && item.type !== '2')) {
        billMain.accountId = ''
        let arr = this.accountIdList.map((v, idx) => {
          let item = {
            id: v,
            money: this.accountMoneyList[idx],
            type: this.accountList.find(val => val.id === v).type
          }
          return item
        })
        this.model.accountList = arr.map(val => {
          let item = this.accountList.find(v => v.id === val.id)
          if (item) {
            return item.name + `(${val.money})`
          }
          return ''
        }).join(',')
      } else {
        // 单账户
        let item = this.accountList.find(v => v.id === accountId)
        if (item) {
          this.model.accountList = item.name + `(${this.$toDecimal(billMain.changeAmount - billMain.backAmount)})`
        }
      }
      //   this.accountIdList = idList
      // this.accountMoneyList = moneyList


      let userInfo = this.getLocalStorage('pro__Login_Userinfo')
      this.model.edit_loginName = userInfo.loginName
      this.model.edit_username = userInfo.username
      billMain.accountIdList = this.accountIdList.length > 0 ? JSON.stringify(this.accountIdList) : ""
      billMain.accountMoneyList = this.accountMoneyList.length > 0 ? JSON.stringify(this.accountMoneyList) : ""
      billMain.custom1 = billMain.custom1 || (this.checkList.length > 0 ? this.checkList.join(',') : '')
      // if(billMain.changeAmount < billMain.totalPrice){
      //   throw new Error(this.$t('setailManagement.collectMoney0'))
      // }

      if (this.model.id) {
        billMain.id = this.model.id
      }
      let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
      return {
        info: JSON.stringify(billMain),
        attachment: fileList,
        rows: JSON.stringify(detailArr),
      }
    },

    checkChangeAmount(rule, value, callback) {
      let totalPrice = this.form.getFieldValue('totalPrice')
      if (+value < totalPrice) {
        callback(false, this.$t('setailManagement.collectMoney0'));
      }
      callback();
    },
    selectAccount(value) {
      if (value === 0) {
        //多账户
        this.$refs.manyAccountModalForm.edit(this.accountIdList, this.defaultMoneyList.split(',') || [])
        this.$refs.manyAccountModalForm.title = this.$t('popup.multiAccountSettlement')
        this.manyAccountBtnStatus = true
      } else {
        let item = this.accountList.find(v => v.id === value)
        if (item && item.type === '2') {

          // this.accountIdList = []
          // this.accountMoneyList = []
          this.manyAccountBtnStatus = false
        }
      }
    },
    /**
     * 
     * @param {array} idList 账户id
     * @param {array} moneyList 支付金额
     * @param {string | number} allPrice 总金额
     * @param {array} checkList 支票
     */
    manyAccountModalFormOk(idList, moneyList, allPrice, checkList) {
      this.defaultMoneyList = moneyList.join(',')
      // 获取选择的账号
      let arr = idList.map((v, idx) => {
        let item = {
          accountList: v,
          money: moneyList[idx],
          type: this.accountList.find(val => val.id === v).type
        }
        return item
      })
      // 现金金额
      let cashAmount = arr.reduce((total, cur) => {
        return total += cur.type === '2' ? cur.money : 0
      }, 0)
      console.log('this.model :>> ', this.model);
      // 重置现金账户金额
      const totalPrice = this.form.getFieldValue('totalPrice') - 0
      const backAmount = toDecimal(allPrice - totalPrice)
      this.accountIdList = idList
      this.accountMoneyList = moneyList
      this.checkList = checkList
      let cashItem = this.accountList.find(v => v.type === '2')
      let index = this.accountIdList.findIndex(v => v === cashItem.id)
      // 有选现金账户
      if (index > -1) {
        console.log('有选现金账户 :>> ', '有选现金账户');
        this.accountMoneyList.splice(index, 1, toDecimal(cashAmount - backAmount))
      } else {
        this.accountMoneyList.push(toDecimal(cashAmount - backAmount))
        this.accountIdList.push(cashItem.id)
      }
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let debt = (discountLastMoney + otherMoney - allPrice).toFixed(2)
      this.$nextTick(() => {
        this.form.setFieldsValue({
          changeAmount: allPrice,
          debt: debt,
          backAmount: this.$toDecimal(allPrice - totalPrice)
        })
      })
      this.$refs.manyAccountModalForm.close()
    },
    onSelectAccount(value) {
      console.log('666 :>> ', value);
      // 重置组件的账户和金额数据
      this.accountIdList = []
      this.accountMoneyList = []
      this.defaultMoneyList = ''
      // 多账户禁用修改支付金额
      if (!value) {
        this.showCheckNumber = true
      } else {
        this.showCheckNumber = false
      }
      let backAmount = this.form.getFieldValue('backAmount')
      this.countAccountMoney(backAmount, value)
      // 显示支票号码
      const item = this.accountList.find(v => v.id === value)
      if (item && item.type == '1') {
        this.showCheck = true
      } else {
        this.showCheck = false
      }
    },
    //加载收款类型
    initPayTypeList() {
      this.payTypeList.push({ "value": "现付", "text": this.$t('popup.cash') })
    },
    //选择会员的触发事件
    onChangeOrgan(value) {
      getAction("/supplier/info", { id: value }).then(res => {
        if (res && res.code === 200) {
          this.payTypeList = []
          let info = res.data.info
          if (info.advanceIn) {
            this.payTypeList.push({ "value": "预付款", "text": this.$t('basicInformation.advanceCharge') + "（" + info.advanceIn + "）" })
            this.payTypeList.push({ "value": "现付", "text": this.$t('popup.cash') })
            this.$nextTick(() => {
              this.form.setFieldsValue({ 'payType': '预付款' })
            })
          } else {
            this.payTypeList.push({ "value": "现付", "text": this.$t('popup.cash') })
          }
        }
      })
    },
    //改变实收金额、收款金额的值
    autoChangePrice(target) {
      let allLastMoney = target.statisticsColumns.allPrice
      this.$nextTick(() => {
        this.form.setFieldsValue({ 'changeAmount': allLastMoney, 'getAmount': allLastMoney, 'backAmount': 0 })
      });
    },
    //改变收款金额
    onKeyUpGetAmount(e) {
      const value = +e.target.value
      let totalPrice = +this.form.getFieldValue('totalPrice')
      let discountMoney = isNaN(this.form.getFieldValue('discountMoney')) ? 0 : this.form.getFieldValue('discountMoney')
      let backAmount = +(value - discountMoney - totalPrice).toFixed(2)
      this.countAccountMoney(backAmount)
      this.$nextTick(() => {
        this.form.setFieldsValue({ 'backAmount': backAmount < 0 ? 0 : backAmount })
      });
    },
    countAccountMoney(backAmount, accountId) {
      accountId = accountId || this.form.getFieldValue('accountId')
      if (!this.showCheckNumber && accountId) {
        // 单账户
        let changeAmount = this.form.getFieldValue('changeAmount')
        let item = this.accountList.find(v => v.id === accountId)
        let cashItem = this.accountList.find(v => v.type === '2')
        if (item && item.type !== '2') {
          // 银行账户
          if (backAmount > 0) {
            this.accountIdList.push(...[accountId, cashItem.id])
            this.accountMoneyList.push(...[changeAmount, -backAmount])
          }
        }
      }
    },

    /**
     * 
     * @param {$enven} e 
     * 改变优惠金额
     */
    onKeyUpdiscountMoney(e) {
      const value = e.target.value || 0
      let totalPrice = +this.form.getFieldValue('totalPrice')
      let changeAmount = +this.form.getFieldValue('changeAmount')
      let backAmount = (changeAmount - value - totalPrice).toFixed(2) - 0
      this.$nextTick(() => {
        this.form.setFieldsValue({ 'backAmount': backAmount })
      });
    },
    retailPrint(name = 'CKXSWJS-detail') {
      console.log('调用了打印 :>> ');
      const Cols = this.materialTable.columns.map(v => {
        let item = {
          name: v.key,
          required: false,
          size: 255,
          type: "str",
          // key:v.dataIndex
        }
        return item
      })
      let dataSource = JSON.parse(this.printData) || []
      const data = dataSource.map(v => {
        let item = {}
        this.materialTable.columns.forEach(val => {
          item[val.key] = v[val.key]
        })
        return item;
      })
      // 表体数据
      let table = {
        Tables: []
      }
      table.Tables[0] = {
        Cols: Cols,
        Data: data,
        Name: 'table'
      }
      // 表头数据
      let ColHead = []

      for (let key in this.model) {
        ColHead.push({
          name: key,
          required: false,
          size: 255,
          type: "str",
        })
      }
      table.Tables[1] = {
        Cols: ColHead,
        Data: [this.model],
        Name: 'headerInfo'
      }
      table.ver = 4,
        table.Copies = 1,
        table.printer = "pdfFactory Pro",
        table.preview = 0,
        table.taskid = "1234567890",
        table.upload_templ_url = "http://192.168.147.1:8081",
        table.upload_templ_user = "myname",
        table.upload_templ_password = "1234567",
        table.upload_templ_comment = this.$route.name
      table.upload_templ_name = this.$route.name
      const templateFileName = name || getFileNameByKey(this.$route.name, getLanCode() === 'en' ? 'en' : 'text')
      table.template = `${templateFileName}.fr3`
      console.log('table :>> ', table);
      const Print = require('@/utils/print/cfprint_ext')
      Print.sendMsg(table)
    },

    /** 发起请求，自动判断是执行新增还是修改操作 */
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true
      if (this.submitBtnDisabled !== undefined) this.submitBtnDisabled = true
      httpAction(url, formData, method)
        .then(res => {
          if (res.code === 200) {
            this.$emit('ok')
            if (this.clearData && typeof this.clearData === 'function') this.clearData()
            if (typeof (this.retailPrint) === "function") this.retailPrint()
            this.confirmLoading = false
            this.close()
          } else {
            this.$message.warning(res.data.message || res.data)
            this.confirmLoading = false
          }
          if (this.submitBtnDisabled !== undefined) this.submitBtnDisabled = false

        })
        .finally(() => { })
        .catch(e => {
          if (this.submitBtnDisabled !== undefined) this.submitBtnDisabled = false
          this.confirmLoading = false
        })
    },
  }
}
</script>
<style scoped>
.sign .ant-input {
  font-size: 30px;
  font-weight: bolder;
  text-align: center;
  border-left-width: 0px !important;
  border-top-width: 0px !important;
  border-right-width: 0px !important;
}
</style>